package com.yym.sina.weibo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cib.yym.homepage.bean.WeiboPost;
import com.cib.yym.homepage.common.CacheManager;
import com.cib.yym.homepage.common.CacheManagerFactory;

public class WeiboServiceImpl implements WeiboService {
	
	public static final String myUid = "2470763803";
	private static final Logger log = Logger.getLogger(WeiboServiceImpl.class.getName());
	
	/**
	 * http://open.weibo.com/wiki/2/statuses/user_timeline
	 * 
	 * @param uid
	 * @return
	 */
	public List<WeiboPost> getRecentUserPost(String uid)
	{
		String serviceUrl = "https://api.weibo.com/2/statuses/user_timeline.json";
		
		String accessToken = null;
		try {
			CacheManager cache = CacheManagerFactory.getCacheManager();
			if(cache.getCachedData(CacheManager.MAP_WEIBO_CONFIG, "accessToken") != null)
			{
				accessToken = (String)cache.getCachedData(CacheManager.MAP_WEIBO_CONFIG, "accessToken");
				log.info("cache hit accessToken="+accessToken);
			}else
            {
            	//TODO redirect to weibo login page
				//throw an exception
				log.info("no accessToken in cache,please redirect to weibo login page");
            }  
        } catch (Exception e) {
        	e.printStackTrace();
        }
		
		String jsonResult = "";
		URL url;
		try {
//			serviceUrl = serviceUrl + "?access_token=" + accessToken
//	        		+"&"+"uid=" + uid 
//	        		+"&"+"count=" + "10";
			serviceUrl = "http://localhost:8080/yym-homepage/test/weibo.json";
			url = new URL(serviceUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        //connection.setDoOutput(true);
	        connection.setDoInput(true);
	        connection.setUseCaches(false);
	        connection.setRequestMethod("GET");
	        connection.connect();
	        
	           
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
          
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // OK
            	 String line;
                 while ((line = reader.readLine()) != null) {                	
                	 jsonResult = jsonResult + line;
                 }
                 reader.close();
                 
                 log.info("jsonResult="+jsonResult);
            } else {
                // Server returned HTTP error code.            	
            	log.info("error http code:"+connection.getResponseCode());
            }             
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		List<WeiboPost> result = new ArrayList();		
		
		try {			
			JSONObject jsonObj = new JSONObject(jsonResult);
			JSONArray array = jsonObj.getJSONArray("statuses");
			for(int i=0;i<array.length();i++)
			{
				WeiboPost p = new WeiboPost();
				JSONObject tmp = array.getJSONObject(i);
				p.setCreatedAt(tmp.optString("created_at"));
				p.setId(tmp.optString("id"));
				p.setContent(tmp.optString("text"));
				p.setOAuthUID(uid);
				p.setUrl(tmp.optString("source"));
				
				//TODO retweeted_status 是原帖
				if( !tmp.isNull("retweeted_status"))
				{
					JSONObject retweeted_status = tmp.getJSONObject("retweeted_status");
					if(retweeted_status!=null)
					{
						WeiboPost retweeted = new WeiboPost();
						retweeted.setId(retweeted_status.optString("id"));
						
						retweeted.setContent(retweeted_status.optString("text"));
						JSONObject originalUser = retweeted_status.getJSONObject("user");
						if(originalUser!=null)
						{
							retweeted.setOAuthUID(originalUser.optString("id"));
							retweeted.setScreenName(originalUser.optString("screen_name"));
						}
						p.setRetweeted(retweeted);
					}
				}
				result.add(p);
			}
			
		} catch (JSONException e) {			
			e.printStackTrace();
		}	
		log.info("result size = "+result.size());
		return result;
	}
}
